package com.eduardcapell.lopodder.io;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;

import org.farng.mp3.MP3File;
import org.farng.mp3.id3.AbstractID3v1;
import org.farng.mp3.id3.AbstractID3v2;
import org.farng.mp3.id3.ID3v1;
import org.farng.mp3.id3.ID3v1_1;
import org.farng.mp3.id3.ID3v2_4;

import com.eduardcapell.lopodder.beans.Feed;
import com.eduardcapell.lopodder.beans.FeedElement;
import com.eduardcapell.lopodder.db.DBAccess;
import com.eduardcapell.lopodder.misc.Utils;

public final class IOUtils {

	private IOUtils() {}

	public static void downloadItem(FeedElement fe) throws Exception {
		String folder = fe.getFeed().getFolder();
		
		if (folder == null) {
			throw new Exception("Folder is null");
		}
		
		File f = new File(folder);
		if (! f.exists()) {
			throw new Exception("Folder does not exist!");
		}
		
		if (!folder.endsWith("/"))	{
			folder = folder + "/";
		}
		
		String fileName = fileFromUrl(fe.getUrl());
		
		fileName = Utils.replaceCharactersInFileName(fileName);
		
		if (fe.getFeed().getRenameFileTo() != null && 
			fe.getFeed().getRenameFileTo().length() > 0) {
			DateFormat df = new SimpleDateFormat("_yyyyMMdd_HHmmss");
			
			String extension = "";
			if (fileName.indexOf('.') > 0) {
				int posDot = fileName.lastIndexOf('.');
				extension = fileName.substring(posDot);
			}
			fileName = fe.getFeed().getRenameFileTo() + df.format(new java.util.Date()) + extension;
		}
		
		fileName = folder + fileName;
		
		
		System.out.println("File is '" + fileName + "'");
		URLConnection conn = null; 

		conn = fe.getUrl().openConnection();
		System.out.println("Downloading " + fe.getUrl().toString());
		InputStream in = conn.getInputStream();
		OutputStream out = new FileOutputStream(new File(fileName));
		byte[] buffer = new byte[1024];
		int numRead = 0;
		long numWritten = 0;
		while ((numRead = in.read(buffer, 0, buffer.length)) != -1) {
			out.write(buffer, 0, numRead);
			numWritten += numRead;
		}
		
		out.flush();
		out.close();

		checkID3tags(fe, fileName);
        fe.setFileName(fileName);
        DBAccess.updateFeedElementFileName(fe);
	}
	
	public static String fileFromUrl(URL url) {
		String u = url.toString();
		int slash = u.lastIndexOf("/");
		String file = u.substring(slash + 1);
		
		int qmark = file.indexOf("?");
		if (qmark >= 0) {
			file = file.substring(0, qmark);
		}
		
		return file;
	}
	
	
	
	public static void checkID3tags(FeedElement fe, String fileName) throws Exception {
		File f = new File(fileName);
		MP3File mp3 = new MP3File(f);
		
		Feed feed = fe.getFeed();
		
		if (mp3.hasID3v1Tag() || mp3.hasID3v2Tag()) {
			return;
		}
		
		DateFormat dfYear = new SimpleDateFormat("yyyy");
		DateFormat dfDate = new SimpleDateFormat("dd/MM/yyyy HH:mm");
		
//		String title = feed.getId3().getSongTitle() + " " + dfDate.format(new java.util.Date());
		String title = fe.getName() + " - " + dfDate.format(new java.util.Date());
		String album = feed.getName();
		String artist = "Artist"; // TODO To implement
		String genre = "Podcast"; // TODO Genre not supported by library in use.
		byte track = 1;
		
		
		ID3v1_1 tag = new ID3v1_1();
		tag.setTitle(title);
		tag.setAlbum(album);
		tag.setArtist(artist);
		tag.setTrack(track);
		tag.setYear(dfYear.format(new java.util.Date()));
		
		mp3.setID3v1Tag(tag);
		mp3.save();
	}
}
